home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 4: GNU Archives / Linux Cubed Series 4 - GNU Archives.iso / gnu / fontutil.6 / fontutil / fontutils-0.6 / limn / fit.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-10-05  |  66.2 KB  |  1,874 lines

  1. /* fit.c: turn a bitmap representation of a curve into a list of splines.
  2.    Some of the ideas, but not the code, comes from the Phoenix thesis. 
  3.    See README for the reference.
  4.  
  5. Copyright (C) 1992 Free Software Foundation, Inc.
  6.  
  7. This program is free software; you can redistribute it and/or modify
  8. it under the terms of the GNU General Public License as published by
  9. the Free Software Foundation; either version 2, or (at your option)
  10. any later version.
  11.  
  12. This program is distributed in the hope that it will be useful,
  13. but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15. GNU General Public License for more details.
  16.  
  17. You should have received a copy of the GNU General Public License
  18. along with this program; if not, write to the Free Software
  19. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  20.  
  21. #include "config.h"
  22.  
  23. #include "logreport.h"
  24. #include "spline.h"
  25. #include "vector.h"
  26.  
  27. #include "curve.h"
  28. #include "display.h"
  29. #include "fit.h"
  30. #include "pxl-outline.h"
  31.  
  32.  
  33. /* If two endpoints are closer than this, they are made to be equal.
  34.    (-align-threshold)  */ 
  35. real align_threshold = 0.5;
  36.  
  37. /* If the angle defined by a point and its predecessors and successors
  38.    is smaller than this, it's a corner, even if it's within
  39.    `corner_surround' pixels of a point with a smaller angle. 
  40.    (-corner-always-threshold)  */
  41. real corner_always_threshold = 60.0;
  42.  
  43. /* Number of points to consider when determining if a point is a corner
  44.    or not.  (-corner-surround)  */
  45. unsigned corner_surround = 4;
  46.  
  47. /* If a point, its predecessors, and its successors define an angle 
  48.     smaller than this, it's a corner.  Should be in range 0..180.
  49.    (-corner-threshold)  */
  50. real corner_threshold = 100.0;
  51.  
  52. /* Amount of error at which a fitted spline is unacceptable.  If any
  53.    pixel is further away than this from the fitted curve, we try again.
  54.    (-error-threshold) */
  55. real error_threshold = .8;
  56.  
  57. /* A second number of adjacent points to consider when filtering.
  58.    (-filter-alternative-surround)  */
  59. unsigned filter_alternative_surround = 1;
  60.  
  61. /* If the angles between the vectors produced by filter_surround and
  62.    filter_alternative_surround points differ by more than this, use
  63.    the one from filter_alternative_surround.  (-filter-epsilon)  */
  64. real filter_epsilon = 10.0;
  65.  
  66. /* Number of times to smooth original data points.  Increasing this
  67.    number dramatically---to 50 or so---can produce vastly better
  68.    results.  But if any points that ``should'' be corners aren't found,
  69.    the curve goes to hell around that point.  (-filter-iterations)  */
  70. unsigned filter_iteration_count = 4;
  71.  
  72. /* To produce the new point, use the old point plus this times the
  73.    neighbors.  (-filter-percent)  */
  74. real filter_percent = .33;
  75.  
  76. /* Number of adjacent points to consider if `filter_surround' points
  77.    defines a straight line.  (-filter-secondary-surround)  */
  78. unsigned filter_secondary_surround = 3;
  79.  
  80. /* Number of adjacent points to consider when filtering.
  81.   (-filter-surround)  */
  82. unsigned filter_surround = 2;
  83.  
  84. /* Says whether or not to remove ``knee'' points after finding the outline. 
  85.    (See the comments at `remove_knee_points'.)  (-remove-knees).  */
  86. boolean keep_knees = false;
  87.  
  88. /* If a spline is closer to a straight line than this, it remains a
  89.    straight line, even if it would otherwise be changed back to a curve.
  90.    This is weighted by the square of the curve length, to make shorter
  91.    curves more likely to be reverted.  (-line-reversion-threshold)  */
  92. real line_reversion_threshold = .01;
  93.  
  94. /* How many pixels (on the average) a spline can diverge from the line
  95.    determined by its endpoints before it is changed to a straight line.
  96.    (-line-threshold) */
  97. real line_threshold = 1.0;
  98.  
  99. /* If reparameterization doesn't improve the fit by this much percent,
  100.    stop doing it.  (-reparameterize-improve)  */
  101. real reparameterize_improvement = .10;
  102.  
  103. /* Amount of error at which it is pointless to reparameterize.  This
  104.    happens, for example, when we are trying to fit the outline of the
  105.    outside of an `O' with a single spline.  The initial fit is not good
  106.    enough for the Newton-Raphson iteration to improve it.  It may be
  107.    that it would be better to detect the cases where we didn't find any
  108.    corners.  (-reparameterize-threshold)  */
  109. real reparameterize_threshold = 30.0;
  110.  
  111. /* Percentage of the curve away from the worst point to look for a
  112.    better place to subdivide.  (-subdivide-search)  */
  113. real subdivide_search = .1;
  114.  
  115. /* Number of points to consider when deciding whether a given point is a
  116.    better place to subdivide.  (-subdivide-surround)  */
  117. unsigned subdivide_surround = 4;
  118.  
  119. /* How many pixels a point can diverge from a straight line and still be
  120.    considered a better place to subdivide.  (-subdivide-threshold) */
  121. real subdivide_threshold = .03;
  122.  
  123. /* Number of points to look at on either side of a point when computing
  124.    the approximation to the tangent at that point.  (-tangent-surround)  */
  125. unsigned tangent_surround = 3;
  126.  
  127. /* We need to manipulate lists of array indices.  */
  128.  
  129. typedef struct index_list
  130. {
  131.   unsigned *data;
  132.   unsigned length;
  133. } index_list_type;
  134.  
  135. /* The usual accessor macros.  */
  136. #define GET_INDEX(i_l, n)  ((i_l).data[n])
  137. #define INDEX_LIST_LENGTH(i_l)  ((i_l).length)
  138. #define GET_LAST_INDEX(i_l)  ((i_l).data[INDEX_LIST_LENGTH (i_l) - 1])
  139.  
  140. static void append_index (index_list_type *, unsigned);
  141. static void free_index_list (index_list_type *);
  142. static index_list_type new_index_list ();
  143. static void remove_adjacent_corners (index_list_type *, unsigned);
  144.  
  145. static void align (spline_list_type *);
  146. static void change_bad_lines (spline_list_type *);
  147. static void filter (curve_type);
  148. static real filter_angle (vector_type, vector_type);
  149. static void find_curve_vectors
  150.   (unsigned, curve_type, unsigned, vector_type *, vector_type *, unsigned *);
  151. static unsigned find_subdivision (curve_type, unsigned initial);
  152. static void find_vectors
  153.   (unsigned, pixel_outline_type, vector_type *, vector_type *);
  154. static index_list_type find_corners (pixel_outline_type);
  155. static real find_error (curve_type, spline_type, unsigned *);
  156. static vector_type find_half_tangent (curve_type, boolean start, unsigned *);
  157. static void find_tangent (curve_type, boolean, boolean);
  158. static spline_type fit_one_spline (curve_type);
  159. static spline_list_type *fit_curve (curve_type);
  160. static spline_list_type fit_curve_list (curve_list_type);
  161. static spline_list_type *fit_with_least_squares (curve_type);
  162. static spline_list_type *fit_with_line (curve_type);
  163. static void remove_knee_points (curve_type, boolean);
  164. static boolean reparameterize (curve_type, spline_type);
  165. static void set_initial_parameter_values (curve_type);
  166. static boolean spline_linear_enough (spline_type *, curve_type);
  167. static curve_list_array_type split_at_corners (pixel_outline_list_type);
  168. static boolean test_subdivision_point (curve_type, unsigned, vector_type *);
  169.  
  170. /* The top-level call that transforms the list of pixels in the outlines
  171.    of the original character to a list of spline lists fitted to those
  172.    pixels.  */
  173.  
  174. spline_list_array_type
  175. fitted_splines (pixel_outline_list_type pixel_outline_list)
  176. {
  177.   unsigned this_list;
  178.   unsigned total = 0;
  179.   spline_list_array_type char_splines = new_spline_list_array ();
  180.   curve_list_array_type curve_array = split_at_corners (pixel_outline_list);
  181.  
  182.   for (this_list = 0; this_list < CURVE_LIST_ARRAY_LENGTH (curve_array);
  183.        this_list++)
  184.     {
  185.       spline_list_type curve_list_splines;
  186.       curve_list_type curves = CURVE_LIST_ARRAY_ELT (curve_array, this_list);
  187.  
  188.       LOG1 ("\nFitting curve list #%u:\n", this_list);
  189.  
  190.       curve_list_splines = fit_curve_list (curves);
  191.       append_spline_list (&char_splines, curve_list_splines);
  192.  
  193.       REPORT ("* ");
  194.     }
  195.  
  196.   free_curve_list_array (&curve_array);
  197.  
  198.   for (this_list = 0; this_list < SPLINE_LIST_ARRAY_LENGTH (char_splines);
  199.        this_list++)
  200.     total
  201.       += SPLINE_LIST_LENGTH (SPLINE_LIST_ARRAY_ELT (char_splines, this_list)); 
  202.  
  203.   REPORT1 ("=%u", total);
  204.  
  205.   return char_splines;
  206. }
  207.  
  208.  
  209. /* Fit the list of curves CURVE_LIST to a list of splines, and return
  210.    it.  CURVE_LIST represents a single closed paths, e.g., either the
  211.    inside or outside outline of an `o'.  */
  212.  
  213. static spline_list_type
  214. fit_curve_list (curve_list_type curve_list)
  215. {
  216.   curve_type curve;
  217.   unsigned this_curve, this_spline;
  218.   unsigned curve_list_length = CURVE_LIST_LENGTH (curve_list);
  219.   spline_list_type curve_list_splines = *new_spline_list ();
  220.  
  221.   /* Remove the extraneous ``knee'' points before filtering.  Since the
  222.      corners have already been found, we don't need to worry about
  223.      removing a point that should be a corner.  */
  224.   if (!keep_knees)
  225.     {
  226.       LOG ("\nRemoving knees:\n");
  227.       for (this_curve = 0; this_curve < curve_list_length; this_curve++)
  228.         {
  229.           LOG1 ("#%u:", this_curve);
  230.           remove_knee_points (CURVE_LIST_ELT (curve_list, this_curve),
  231.                               CURVE_LIST_CLOCKWISE (curve_list));
  232.         }
  233.     }
  234.  
  235.   /* We filter all the curves in CURVE_LIST at once; otherwise, we would
  236.      look at an unfiltered curve when computing tangents.  */
  237.   LOG ("\nFiltering curves:\n");
  238.   for (this_curve = 0; this_curve < curve_list.length; this_curve++)
  239.     {
  240.       LOG1 ("#%u: ", this_curve);
  241.       filter (CURVE_LIST_ELT (curve_list, this_curve));
  242.       REPORT ("f");
  243.     }
  244.  
  245.   /* Make the first point in the first curve also be the last point in
  246.      the last curve, so the fit to the whole curve list will begin and
  247.      end at the same point.  This may cause slight errors in computing
  248.      the tangents and t values, but it's worth it for the continuity.
  249.      Of course we don't want to do this if the two points are already
  250.      the same, as they are if the curve is cyclic.  (We don't append it
  251.      earlier, in `split_at_corners', because that confuses the
  252.      filtering.)  Finally, we can't append the point if the curve is
  253.      exactly three points long, because we aren't adding any more data,
  254.      and three points isn't enough to determine a spline.  Therefore,
  255.      the fitting will fail.  */
  256.   curve = CURVE_LIST_ELT (curve_list, 0);
  257.   if (CURVE_CYCLIC (curve) && CURVE_LENGTH (curve) != 3)
  258.     append_point (curve, CURVE_POINT (curve, 0));
  259.  
  260.   /* Finally, fit each curve in the list to a list of splines.  */
  261.   for (this_curve = 0; this_curve < curve_list_length; this_curve++)
  262.     {
  263.       spline_list_type *curve_splines;
  264.       curve_type current_curve = CURVE_LIST_ELT (curve_list, this_curve);
  265.  
  266.       REPORT1 (" %u", this_curve);
  267.       LOG1 ("\nFitting curve #%u:\n", this_curve);
  268.  
  269.       curve_splines = fit_curve (current_curve);
  270.       if (curve_splines == NULL)
  271.         WARNING1 ("Could not fit curve #%u", this_curve);
  272.       else
  273.         {
  274.           LOG1 ("Fitted splines for curve #%u:\n", this_curve);
  275.           for (this_spline = 0;
  276.                this_spline < SPLINE_LIST_LENGTH (*curve_splines); 
  277.                this_spline++)
  278.             {
  279.               LOG1 ("  %u: ", this_spline);
  280.               if (logging)
  281.                 print_spline (log_file,
  282.                               SPLINE_LIST_ELT (*curve_splines, this_spline));
  283.             }
  284.  
  285.           /* After fitting, we may need to change some would-be lines
  286.              back to curves, because they are in a list with other
  287.              curves.  */
  288.           change_bad_lines (curve_splines);
  289.  
  290.           concat_spline_lists (&curve_list_splines, *curve_splines);
  291.           REPORT1 ("(%u)", SPLINE_LIST_LENGTH (*curve_splines));
  292.         }
  293.     }
  294.  
  295.   if (logging)
  296.     {
  297.       LOG ("\nFitted splines are:\n");
  298.       for (this_spline = 0; this_spline < SPLINE_LIST_LENGTH (curve_list_splines);
  299.            this_spline++)
  300.         {
  301.           LOG1 ("  %u: ", this_spline);
  302.           print_spline (log_file, SPLINE_LIST_ELT (curve_list_splines,
  303.                                                    this_spline));
  304.         }
  305.     }
  306.  
  307.   /* We do this for each outline's spline list because when a point
  308.      is changed, it needs to be changed in both segments in which it
  309.      appears---and the segments might be in different curves.  */
  310.   align (&curve_list_splines);
  311.  
  312.   return curve_list_splines;
  313. }
  314.  
  315.  
  316. /* Transform a set of locations to a list of splines (the fewer the
  317.    better).  We are guaranteed that CURVE does not contain any corners.
  318.    We return NULL if we cannot fit the points at all.  */
  319.  
  320. static spline_list_type *
  321. fit_curve (curve_type curve)
  322. {
  323.   spline_list_type *fitted_splines;
  324.  
  325.   if (CURVE_LENGTH (curve) < 2)
  326.     {
  327.       WARNING ("Tried to fit curve with less than two points");
  328.       return NULL;
  329.     }
  330.  
  331.   /* Do we have enough points to fit with a spline?  */
  332.   fitted_splines = CURVE_LENGTH (curve) < 4
  333.                    ? fit_with_line (curve) 
  334.                    : fit_with_least_squares (curve);
  335.  
  336.   return fitted_splines;
  337. }
  338.  
  339. /* As mentioned above, the first step is to find the corners in
  340.    PIXEL_LIST, the list of points.  (Presumably we can't fit a single
  341.    spline around a corner.)  The general strategy is to look through all
  342.    the points, remembering which we want to consider corners.  Then go
  343.    through that list, producing the curve_list.  This is dictated by the
  344.    fact that PIXEL_LIST does not necessarily start on a corner---it just
  345.    starts at the character's first outline pixel, going left-to-right,
  346.    top-to-bottom.  But we want all our splines to start and end on real
  347.    corners.
  348.  
  349.    For example, consider the top of a capital `C' (this is in cmss20):
  350.                      x
  351.                      ***********
  352.                   ******************
  353.  
  354.    PIXEL_LIST will start at the pixel below the `x'.  If we considered
  355.    this pixel a corner, we would wind up matching a very small segment
  356.    from there to the end of the line, probably as a straight line, which
  357.    is certainly not what we want.  
  358.  
  359.    PIXEL_LIST has one element for each closed outline on the character.
  360.    To preserve this information, we return an array of curve_lists, one
  361.    element (which in turn consists of several curves, one between each
  362.    pair of corners) for each element in PIXEL_LIST.  */
  363.  
  364. static curve_list_array_type
  365. split_at_corners (pixel_outline_list_type pixel_list)
  366. {
  367.   unsigned this_pixel_o;
  368.   curve_list_array_type curve_array = new_curve_list_array ();
  369.  
  370.   LOG ("\nFinding corners:\n");
  371.  
  372.   for (this_pixel_o = 0; this_pixel_o < O_LIST_LENGTH (pixel_list);
  373.        this_pixel_o++)
  374.     {
  375.       curve_type curve, first_curve;
  376.       index_list_type corner_list;
  377.       unsigned p, this_corner;
  378.       curve_list_type curve_list = new_curve_list ();
  379.       pixel_outline_type pixel_o = O_LIST_OUTLINE (pixel_list, this_pixel_o);
  380.  
  381.       CURVE_LIST_CLOCKWISE (curve_list) = O_CLOCKWISE (pixel_o);
  382.       
  383.       LOG1 ("#%u:", this_pixel_o);
  384.  
  385.       /* If the outline does not have enough points, we can't do
  386.          anything.  The endpoints of the outlines are automatically
  387.          corners.  We need at least `corner_surround' more pixels on
  388.          either side of a point before it is conceivable that we might
  389.          want another corner.  */
  390.       if (O_LENGTH (pixel_o) > corner_surround * 2 + 2)
  391.         corner_list = find_corners (pixel_o);
  392.       else
  393.         corner_list.length = 0;
  394.  
  395.       /* Remember the first curve so we can make it be the `next' of the
  396.          last one.  (And vice versa.)  */
  397.       first_curve = new_curve ();
  398.  
  399.       curve = first_curve;
  400.  
  401.       if (corner_list.length == 0)
  402.         { /* No corners.  Use all of the pixel outline as the curve.  */
  403.           for (p = 0; p < O_LENGTH (pixel_o); p++)
  404.             append_pixel (curve, O_COORDINATE (pixel_o, p));
  405.  
  406.           /* This curve is cyclic.  */
  407.           CURVE_CYCLIC (curve) = true;
  408.         }
  409.       else
  410.         { /* Each curve consists of the points between (inclusive) each pair
  411.              of corners.  */
  412.           for (this_corner = 0; this_corner < corner_list.length - 1;
  413.                this_corner++)
  414.             {
  415.               curve_type previous_curve = curve;
  416.               unsigned corner = GET_INDEX (corner_list, this_corner);
  417.               unsigned next_corner = GET_INDEX (corner_list, this_corner + 1);
  418.  
  419.               for (p = corner; p <= next_corner; p++)
  420.                 append_pixel (curve, O_COORDINATE (pixel_o, p));
  421.  
  422.               append_curve (&curve_list, curve);
  423.               curve = new_curve ();
  424.               NEXT_CURVE (previous_curve) = curve;
  425.               PREVIOUS_CURVE (curve) = previous_curve;
  426.             }
  427.  
  428.           /* The last curve is different.  It consists of the points
  429.              (inclusive) between the last corner and the end of the list,
  430.              and the beginning of the list and the first corner.  */
  431.           for (p = GET_LAST_INDEX (corner_list); p < O_LENGTH (pixel_o);
  432.                p++)
  433.             append_pixel (curve, O_COORDINATE (pixel_o, p));
  434.  
  435.           for (p = 0; p <= GET_INDEX (corner_list, 0); p++)
  436.             append_pixel (curve, O_COORDINATE (pixel_o, p));
  437.         }
  438.  
  439.       LOG1 (" [%u].\n", corner_list.length);
  440.  
  441.       /* Add `curve' to the end of the list, updating the pointers in
  442.          the chain.  */
  443.       append_curve (&curve_list, curve);
  444.       NEXT_CURVE (curve) = first_curve;
  445.       PREVIOUS_CURVE (first_curve) = curve;
  446.  
  447.       /* And now add the just-completed curve list to the array.  */
  448.       append_curve_list (&curve_array, curve_list);
  449.     }                /* End of considering each pixel outline.  */
  450.  
  451.   return curve_array;
  452. }
  453.  
  454.  
  455. /* We consider a point to be a corner if (1) the angle defined by the
  456.    `corner_surround' points coming into it and going out from it is less
  457.    than `corner_threshold' degrees, and no point within
  458.    `corner_surround' points has a smaller angle; or (2) the angle is less
  459.    than `corner_always_threshold' degrees.
  460.  
  461.    Because of the different cases, it is convenient to have the
  462.    following macro to append a corner on to the list we return.  The
  463.    character argument C is simply so that the different cases can be
  464.    distinguished in the log file.  */
  465.  
  466. #define APPEND_CORNER(index, angle, c)                    \
  467.   do                                    \
  468.     {                                    \
  469.       append_index (&corner_list, index);                \
  470.       if (wants_display)                        \
  471.         display_corner (O_COORDINATE (pixel_outline, index));        \
  472.       LOG4 (" (%d,%d)%c%.3f",                        \
  473.             O_COORDINATE (pixel_outline, index).x,            \
  474.             O_COORDINATE (pixel_outline, index).y,            \
  475.             c, angle);                            \
  476.     }                                    \
  477.   while (0)
  478.  
  479. static index_list_type
  480. find_corners (pixel_outline_type pixel_outline)
  481. {
  482.   unsigned p;
  483.   index_list_type corner_list = new_index_list ();
  484.  
  485.   /* Consider each pixel on the outline in turn.  */
  486.   for (p = 0; p < O_LENGTH (pixel_outline); p++)
  487.     {
  488.       real corner_angle;
  489.       vector_type in_vector, out_vector;
  490.  
  491.       /* Check if the angle is small enough.  */
  492.       find_vectors (p, pixel_outline, &in_vector, &out_vector);
  493.       corner_angle = Vangle (in_vector, out_vector);
  494.  
  495.       if (fabs (corner_angle) <= corner_threshold)
  496.         {
  497.           /* We want to keep looking, instead of just appending the
  498.              first pixel we find with a small enough angle, since there
  499.              might be another corner within `corner_surround' pixels, with
  500.              a smaller angle.  If that is the case, we want that one.  */
  501.           real best_corner_angle = corner_angle;
  502.           unsigned best_corner_index = p;
  503.           index_list_type equally_good_list = new_index_list ();
  504.           /* As we come into the loop, `p' is the index of the point
  505.              that has an angle less than `corner_angle'.  We use `i' to
  506.              move through the pixels next to that, and `q' for moving
  507.              through the adjacent pixels to each `p'.  */
  508.           unsigned q = p;
  509.           unsigned i = p + 1;
  510.  
  511.           while (true)
  512.             {
  513.               /* Perhaps the angle is sufficiently small that we want to
  514.                  consider this a corner, even if it's not the best
  515.                  (unless we've already wrapped around in the search,
  516.                  i.e., `q<i', in which case we have already added the
  517.                  corner, and we don't want to add it again).  We want to
  518.                  do this check on the first candidate we find, as well
  519.                  as the others in the loop, hence this comes before the
  520.                  stopping condition.  */
  521.               if (corner_angle <= corner_always_threshold && q >= p)
  522.                 APPEND_CORNER (q, corner_angle, '\\');
  523.  
  524.               /* Exit the loop if we've looked at `corner_surround'
  525.                  pixels past the best one we found, or if we've looked
  526.                  at all the pixels.  */
  527.               if (i >= best_corner_index + corner_surround
  528.                   || i >= O_LENGTH (pixel_outline))
  529.                 break;
  530.  
  531.               /* Check the angle.  */
  532.               q = i % O_LENGTH (pixel_outline);
  533.               find_vectors (q, pixel_outline, &in_vector, &out_vector);
  534.               corner_angle = Vangle (in_vector, out_vector);
  535.  
  536.               /* If we come across a corner that is just as good as the
  537.                  best one, we should make it a corner, too.  This
  538.                  happens, for example, at the points on the `W' in some
  539.                  typefaces, where the ``points'' are flat.  */
  540.               if (epsilon_equal (corner_angle, best_corner_angle))
  541.                 append_index (&equally_good_list, q);
  542.  
  543.               else if (corner_angle < best_corner_angle)
  544.                 {
  545.                   best_corner_angle = corner_angle;
  546.                   /* We want to check `corner_surround' pixels beyond the
  547.                      new best corner.  */
  548.                   i = best_corner_index = q;
  549.                   free_index_list (&equally_good_list);
  550.                   equally_good_list = new_index_list ();
  551.                 }
  552.  
  553.               i++;
  554.             }
  555.  
  556.           /* After we exit the loop, `q' is the index of the last point
  557.              we checked.  We have already added the corner if
  558.              `best_corner_angle' is less than `corner_always_threshold'.
  559.              Again, if we've already wrapped around, we don't want to
  560.              add the corner again.  */
  561.           if (best_corner_angle > corner_always_threshold
  562.               && best_corner_index >= p)
  563.             {
  564.               unsigned i;
  565.  
  566.               APPEND_CORNER (best_corner_index, best_corner_angle, '/');
  567.  
  568.               for (i = 0; i < INDEX_LIST_LENGTH (equally_good_list); i++)
  569.                 APPEND_CORNER (GET_INDEX (equally_good_list, i),
  570.                                best_corner_angle, '@');
  571.               free_index_list (&equally_good_list);
  572.             }
  573.  
  574.           /* If we wrapped around in our search, we're done; otherwise,
  575.              we don't want the outer loop to look at the pixels that we
  576.              already looked at in searching for the best corner.  */
  577.           p = (q < p) ? O_LENGTH (pixel_outline) : q;
  578.         }            /* End of searching for the best corner.  */
  579.     }                /* End of considering each pixel.  */
  580.  
  581.   if (INDEX_LIST_LENGTH (corner_list) > 0)
  582.     /* We never want two corners next to each other, since the
  583.        only way to fit such a ``curve'' would be with a straight
  584.        line, which usually interrupts the continuity dreadfully.  */
  585.     remove_adjacent_corners (&corner_list, O_LENGTH (pixel_outline) - 1);
  586.           
  587.   return corner_list;
  588. }
  589.  
  590.  
  591. /* Return the difference vectors coming in and going out of the outline
  592.    OUTLINE at the point whose index is TEST_INDEX.  In Phoenix,
  593.    Schneider looks at a single point on either side of the point we're
  594.    considering.  That works for him because his points are not touching.
  595.    But our points *are* touching, and so we have to look at
  596.    `corner_surround' points on either side, to get a better picture of
  597.    the outline's shape.  */
  598.  
  599. static void
  600. find_vectors (unsigned test_index, pixel_outline_type outline,
  601.               vector_type *in, vector_type *out)
  602. {
  603.   int i;
  604.   unsigned n_done;
  605.   coordinate_type candidate = O_COORDINATE (outline, test_index);
  606.  
  607.   *in = (vector_type) { 0.0, 0.0 };
  608.   *out = (vector_type) { 0.0, 0.0 };
  609.  
  610.   /* Add up the differences from p of the `corner_surround' points
  611.      before p.  */ 
  612.   for (i = O_PREV (outline, test_index), n_done = 0; n_done < corner_surround;
  613.        i = O_PREV (outline, i), n_done++)
  614.     *in = Vadd (*in, IPsubtract (O_COORDINATE (outline, i), candidate));
  615.  
  616. #if 0
  617.   /* We don't need this code any more, because now we create the pixel
  618.      outline from the corners of the pixels, rather than the edges.  */
  619.  
  620.   /* To see why we need this test, consider the following
  621.      case: four pixels stacked vertically with no other adjacent pixels,
  622.      i.e.,   *
  623.              *x
  624.              *
  625.              *
  626.             *** (etc.) We are considering the pixel marked `x' for cornerhood.
  627.      The out vector at this point is going to be the zero vector (if
  628.      `corner_surround' is 3), because the first
  629.      pixel on the outline is the one above the x, the second pixel x
  630.      itself, and the third the one below x.  (Remember that we go
  631.      around the edges of the pixels to find the outlines, not the
  632.      pixels themselves.)  */
  633.   if (magnitude (*in) == 0.0)
  634.     {
  635.       WARNING ("Zero magnitude in");
  636.       return corner_threshold + 1.0;
  637.     }
  638. #endif /* 0 */
  639.  
  640.   /* And the points after p.  */
  641.   for (i = O_NEXT (outline, test_index), n_done = 0; n_done < corner_surround;
  642.        i = O_NEXT (outline, i), n_done++)
  643.     *out = Vadd (*out, IPsubtract (O_COORDINATE (outline, i), candidate));
  644.  
  645. #if 0
  646.   /* As with the test for the in vector, we don't need this any more.  */
  647.   if (magnitude (*out) == 0.0)
  648.     {
  649.       WARNING ("Zero magnitude out");
  650.       return corner_threshold + 1.0;
  651.     }
  652. #endif /* 0 */
  653. }
  654.  
  655.  
  656. /* Remove adjacent points from the index list LIST.  We do this by first
  657.    sorting the list and then running through it.  Since these lists are
  658.    quite short, a straight selection sort (e.g., p.139 of the Art of
  659.    Computer Programming, vol.3) is good enough.  LAST_INDEX is the index
  660.    of the last pixel on the outline, i.e., the next one is the first
  661.    pixel.  We need this for checking the adjacency of the last corner.
  662.    
  663.    We need to do this because the adjacent corners turn into
  664.    two-pixel-long curves, which can only be fit by straight lines.  */
  665.  
  666. static void
  667. remove_adjacent_corners (index_list_type *list, unsigned last_index)
  668. {
  669.   unsigned j;
  670.   unsigned last;
  671.   index_list_type new = new_index_list ();
  672.   
  673.   for (j = INDEX_LIST_LENGTH (*list) - 1; j > 0; j--)
  674.     {
  675.       unsigned search;
  676.       unsigned temp;
  677.       /* Find maximal element below `j'.  */
  678.       unsigned max_index = j;
  679.       
  680.       for (search = 0; search < j; search++)
  681.         if (GET_INDEX (*list, search) > GET_INDEX (*list, max_index))
  682.           max_index = search;
  683.           
  684.       if (max_index != j)
  685.         {
  686.           temp = GET_INDEX (*list, j);
  687.           GET_INDEX (*list, j) = GET_INDEX (*list, max_index);
  688.           GET_INDEX (*list, max_index) = temp;
  689.           WARNING ("needed exchange"); /* xx -- really have to sort?  */
  690.         }
  691.     }
  692.   
  693.   /* The list is sorted.  Now look for adjacent entries.  Each time
  694.      through the loop we insert the current entry and, if appropriate,
  695.      the next entry.  */
  696.   for (j = 0; j < INDEX_LIST_LENGTH (*list) - 1; j++)
  697.     {
  698.       unsigned current = GET_INDEX (*list, j);
  699.       unsigned next = GET_INDEX (*list, j + 1);
  700.       
  701.       /* We should never have inserted the same element twice.  */
  702.       assert (current != next);
  703.       
  704.       append_index (&new, current);
  705.       if (next == current + 1)
  706.         j++;
  707.     }
  708.   
  709.   /* Don't append the last element if it is 1) adjacent to the previous
  710.      one; or 2) adjacent to the very first one.  */
  711.   last = GET_LAST_INDEX (*list);
  712.   if (INDEX_LIST_LENGTH (new) == 0
  713.       || !(last == GET_LAST_INDEX (new) + 1
  714.            || (last == last_index && GET_INDEX (*list, 0) == 0)))
  715.     append_index (&new, last);
  716.   
  717.   free_index_list (list);
  718.   *list = new;
  719. }
  720.  
  721. /* A ``knee'' is a point which forms a ``right angle'' with its
  722.    predecessor and successor.  See the documentation (the `Removing
  723.    knees' section) for an example and more details.
  724.  
  725.    The argument CLOCKWISE tells us which direction we're moving.  (We
  726.    can't figure that information out from just the single segment with
  727.    which we are given to work.)
  728.    
  729.    We should never find two consecutive knees.
  730.    
  731.    Since the first and last points are corners (unless the curve is
  732.    cyclic), it doesn't make sense to remove those.  */
  733.  
  734. /* This evaluates to true if the vector V is zero in one direction and
  735.    nonzero in the other.  */
  736. #define ONLY_ONE_ZERO(v)                        \
  737.   (((v).dx == 0.0 && (v).dy != 0.0) || ((v).dy == 0.0 && (v).dx != 0.0))
  738.  
  739.  
  740. /* There are four possible cases for knees, one for each of the four
  741.    corners of a rectangle; and then the cases differ depending on which
  742.    direction we are going around the curve.  The tests are listed here
  743.    in the order of upper left, upper right, lower right, lower left.
  744.    Perhaps there is some simple pattern to the
  745.    clockwise/counterclockwise differences, but I don't see one.  */
  746. #define CLOCKWISE_KNEE(prev_delta, next_delta)                \
  747.   ((prev_delta.dx == -1.0 && next_delta.dy == 1.0)            \
  748.    || (prev_delta.dy == 1.0 && next_delta.dx == 1.0)            \
  749.    || (prev_delta.dx == 1.0 && next_delta.dy == -1.0)            \
  750.    || (prev_delta.dy == -1.0 && next_delta.dx == -1.0))
  751.  
  752. #define COUNTERCLOCKWISE_KNEE(prev_delta, next_delta)            \
  753.   ((prev_delta.dy == 1.0 && next_delta.dx == -1.0)            \
  754.    || (prev_delta.dx == 1.0 && next_delta.dy == 1.0)            \
  755.    || (prev_delta.dy == -1.0 && next_delta.dx == 1.0)            \
  756.    || (prev_delta.dx == -1.0 && next_delta.dy == -1.0))
  757.  
  758. static void
  759. remove_knee_points (curve_type curve, boolean clockwise)
  760. {
  761.   int i;
  762.   unsigned offset = CURVE_CYCLIC (curve) ? 0 : 1;
  763.   coordinate_type previous
  764.     = real_to_int_coord (CURVE_POINT (curve, CURVE_PREV (curve, offset))); 
  765.   curve_type trimmed_curve = copy_most_of_curve (curve);
  766.   
  767.   if (!CURVE_CYCLIC (curve))
  768.     append_pixel (trimmed_curve, real_to_int_coord (CURVE_POINT (curve, 0)));
  769.  
  770.   for (i = offset; i < CURVE_LENGTH (curve) - offset; i++)
  771.     {
  772.       coordinate_type current
  773.         = real_to_int_coord (CURVE_POINT (curve, i));
  774.       coordinate_type next
  775.         = real_to_int_coord (CURVE_POINT (curve, CURVE_NEXT (curve, i)));
  776.       vector_type prev_delta = IPsubtract (previous, current);
  777.       vector_type next_delta = IPsubtract (next, current);
  778.  
  779.       if (ONLY_ONE_ZERO (prev_delta) && ONLY_ONE_ZERO (next_delta)
  780.           && ((clockwise && CLOCKWISE_KNEE (prev_delta, next_delta))
  781.               || (!clockwise
  782.                   && COUNTERCLOCKWISE_KNEE (prev_delta, next_delta))))
  783.         LOG2 (" (%d,%d)", current.x, current.y);
  784.       else
  785.         {
  786.           previous = current;
  787.           append_pixel (trimmed_curve, current);
  788.         }
  789.     }
  790.  
  791.   if (!CURVE_CYCLIC (curve))
  792.     append_pixel (trimmed_curve, real_to_int_coord (LAST_CURVE_POINT (curve)));
  793.  
  794.   if (CURVE_LENGTH (trimmed_curve) == CURVE_LENGTH (curve))
  795.     LOG (" (none)");
  796.  
  797.   LOG (".\n");
  798.  
  799.   free_curve (curve);
  800.   *curve = *trimmed_curve;
  801. }
  802.  
  803. /* Smooth the curve by adding in neighboring points.  Do this
  804.    `filter_iteration_count' times.  But don't change the corners.  */
  805.  
  806. #if 0
  807. /* Computing the new point based on a single neighboring point and with
  808.    constant percentages, as the `SMOOTH' macro did, isn't quite good
  809.    enough.  For example, at the top of an `o' the curve might well have
  810.    three consecutive horizontal pixels, even though there isn't really a
  811.    straight there.  With this code, the middle point would remain
  812.    unfiltered.  */
  813.  
  814. #define SMOOTH(axis)                            \
  815.   CURVE_POINT (curve, this_point).axis                    \
  816.     = ((1.0 - center_percent) / 2)                    \
  817.        * CURVE_POINT (curve, CURVE_PREV (curve, this_point)).axis       \
  818.       + center_percent * CURVE_POINT (curve, this_point).axis        \
  819.       + ((1.0 - center_percent) / 2)                    \
  820.         * CURVE_POINT (curve, CURVE_NEXT (curve, this_point)).axis
  821. #endif /* 0 */
  822.  
  823. /* We sometimes need to change the information about the filtered point.
  824.    This macro assigns to the relevant variables.  */
  825. #define FILTER_ASSIGN(new)                        \
  826.   do                                    \
  827.     {                                    \
  828.       in = in_##new;                            \
  829.       out = out_##new;                            \
  830.       count = new##_count;                        \
  831.       angle = angle_##new;                        \
  832.     }                                    \
  833.   while (0)
  834.  
  835. static void
  836. filter (curve_type curve)
  837. {
  838.   unsigned iteration, this_point;
  839.   unsigned offset = CURVE_CYCLIC (curve) ? 0 : 1;
  840.  
  841.   /* We must have at least three points---the previous one, the current
  842.      one, and the next one.  But if we don't have at least five, we will
  843.      probably collapse the curve down onto a single point, which means
  844.      we won't be able to fit it with a spline.  */
  845.   if (CURVE_LENGTH (curve) < 5)
  846.     {
  847.       LOG1 ("Length is %u, not enough to filter.\n", CURVE_LENGTH (curve));
  848.       return;
  849.     }
  850.  
  851.   for (iteration = 0; iteration < filter_iteration_count; iteration++)
  852.     {
  853.       curve_type new_curve = copy_most_of_curve (curve);
  854.       
  855.       /* Keep the first point on the curve.  */
  856.       if (offset)
  857.         append_point (new_curve, CURVE_POINT (curve, 0));
  858.  
  859.       for (this_point = offset; this_point < CURVE_LENGTH (curve) - offset;
  860.            this_point++)
  861.         {
  862.           real angle, angle_alt;
  863.           vector_type in, in_alt, out, out_alt, sum;
  864.           unsigned count, alt_count;
  865.           real_coordinate_type new_point;
  866.  
  867.           /* Find the angle using the usual number of surrounding points
  868.              on the curve. */
  869.           find_curve_vectors (this_point, curve, filter_surround,
  870.                               &in, &out, &count);
  871.           angle = filter_angle (in, out);
  872.  
  873.           /* Find the angle using the alternative (presumably smaller)
  874.              number.  */ 
  875.           find_curve_vectors (this_point, curve, filter_alternative_surround,
  876.                               &in_alt, &out_alt, &alt_count);
  877.           angle_alt = filter_angle (in_alt, out_alt);
  878.  
  879.           /* If the alternate angle is enough larger than the usual one
  880.              and neither of the components of the sum are zero, use it.
  881.              (We don't use absolute value here, since if the alternate
  882.              angle is smaller, we don't particularly care, since that
  883.              means the curve is pretty flat around the current point,
  884.              anyway.)  This helps keep small features from disappearing
  885.              into the surrounding curve.  */
  886.           sum = Vadd (in_alt, out_alt);
  887.           if (angle_alt - angle >= filter_epsilon
  888.               && sum.dx != 0 && sum.dy != 0)
  889.             FILTER_ASSIGN (alt);
  890.  
  891. #if 0
  892. /* This code isn't needed anymore, since we do the filtering in a
  893.    somewhat more general way.  */
  894.           /* If we're left with an angle of zero, don't stop yet; we
  895.              might be at a straight which really isn't one (as in the `o'
  896.              discussed above).  */
  897.           if (epsilon_equal (angle, 0.0))
  898.             {
  899.               real angle_secondary;
  900.               vector_type in_secondary, out_secondary;
  901.               unsigned in_secondary_count, out_secondary_count;
  902.  
  903.               find_curve_vectors (this_point, curve, filter_secondary_surround,
  904.                                   &in_secondary, &out_secondary,
  905.                                   &in_secondary_count, &out_secondary_count);
  906.               angle_secondary = filter_angle (in_secondary, out_secondary);
  907.               if (!epsilon_equal (angle_secondary, 0.0))
  908.                 FILTER_ASSIGN (secondary);
  909.             }
  910. #endif /* 0 */
  911.  
  912.           /* Start with the old point.  */
  913.           new_point = CURVE_POINT (curve, this_point);
  914.           sum = Vadd (in, out);
  915.           new_point.x += sum.dx * filter_percent / count;
  916.           new_point.y += sum.dy * filter_percent / count;
  917.  
  918.           /* Put the newly computed point into a separate curve, so it
  919.              doesn't affect future computation (on this iteration).  */
  920.           append_point (new_curve, new_point);
  921.        }
  922.      
  923.      /* Just as with the first point, we have to keep the last point.  */
  924.      if (offset)
  925.        append_point (new_curve, LAST_CURVE_POINT (curve));
  926.        
  927.      /* Set the original curve to the newly filtered one, and go again.  */
  928.      free_curve (curve);
  929.      *curve = *new_curve;
  930.     }
  931.  
  932.   log_curve (curve, false);
  933.   display_curve (curve);
  934. }
  935.  
  936.  
  937. /* Return the vectors IN and OUT, computed by looking at SURROUND points
  938.    on either side of TEST_INDEX.  Also return the number of points in
  939.    the vectors in COUNT (we make sure they are the same).  */
  940.  
  941. static void
  942. find_curve_vectors (unsigned test_index, curve_type curve,
  943.                     unsigned surround,
  944.                     vector_type *in, vector_type *out, unsigned *count)
  945. {
  946.   int i;
  947.   unsigned in_count, out_count;
  948.   unsigned n_done;
  949.   real_coordinate_type candidate = CURVE_POINT (curve, test_index);
  950.  
  951.   /* Add up the differences from p of the `surround' points
  952.      before p.  */ 
  953.   *in = (vector_type) { 0.0, 0.0 };
  954.   for (i = CURVE_PREV (curve, test_index), n_done = 0;
  955.        i >= 0 && n_done < surround;  /* Do not wrap around.  */
  956.        i = CURVE_PREV (curve, i), n_done++)
  957.     *in = Vadd (*in, Psubtract (CURVE_POINT (curve, i), candidate));
  958.   in_count = n_done;
  959.  
  960.   /* And the points after p.  Don't use more points after p than we
  961.      ended up with before it.  */
  962.   *out = (vector_type) { 0.0, 0.0 };
  963.   for (i = CURVE_NEXT (curve, test_index), n_done = 0;
  964.        i < CURVE_LENGTH (curve) && n_done < surround && n_done < in_count;
  965.        i = CURVE_NEXT (curve, i), n_done++)
  966.     *out = Vadd (*out, Psubtract (CURVE_POINT (curve, i), candidate));
  967.   out_count = n_done;
  968.   
  969.   /* If we used more points before p than after p, we have to go back
  970.      and redo it.  (We could just subtract the ones that were missing,
  971.      but for this few of points, efficiency doesn't matter.)  */
  972.   if (out_count < in_count)
  973.     {
  974.       *in = (vector_type) { 0.0, 0.0 };
  975.       for (i = CURVE_PREV (curve, test_index), n_done = 0;
  976.            i >= 0 && n_done < out_count;
  977.            i = CURVE_PREV (curve, i), n_done++)
  978.         *in = Vadd (*in, Psubtract (CURVE_POINT (curve, i), candidate));
  979.       in_count = n_done;
  980.     }
  981.   
  982.   assert (in_count == out_count);
  983.   *count = in_count;
  984. }
  985.  
  986.  
  987. /* Find the angle between the vectors IN and OUT, and bring it into the
  988.    range [0,45].  */
  989.  
  990. static real
  991. filter_angle (vector_type in, vector_type out)
  992. {
  993.   real angle = Vangle (in, out);
  994.   
  995.   /* What we want to do between 90 and 180 is the same as what we
  996.      want to do between 0 and 90.  */
  997.   angle = fmod (angle, 1990.0);
  998.  
  999.   /* And what we want to do between 45 and 90 is the same as
  1000.      between 0 and 45, only reversed.  */
  1001.   if (angle > 45.0) angle = 90.0 - angle;
  1002.  
  1003.   return angle;
  1004. }
  1005.  
  1006. /* This routine returns the curve fitted to a straight line in a very
  1007.    simple way: make the first and last points on the curve be the
  1008.    endpoints of the line.  This simplicity is justified because we are
  1009.    called only on very short curves.  */
  1010.  
  1011. static spline_list_type *
  1012. fit_with_line (curve_type curve)
  1013. {
  1014.   spline_type line = new_spline ();
  1015.  
  1016.   LOG ("Fitting with straight line:\n");
  1017.   REPORT ("l");
  1018.  
  1019.   SPLINE_DEGREE (line) = LINEAR;
  1020.   START_POINT (line) = CONTROL1 (line) = CURVE_POINT (curve, 0);
  1021.   END_POINT (line) = CONTROL2 (line) = LAST_CURVE_POINT (curve);
  1022.   
  1023.   /* Make sure that this line is never changed to a cubic.  */
  1024.   SPLINE_LINEARITY (line) = 0;
  1025.  
  1026.   if (logging)
  1027.     {
  1028.       LOG ("  ");
  1029.       print_spline (log_file, line);
  1030.     }
  1031.  
  1032.   return init_spline_list (line);
  1033. }
  1034.  
  1035. /* The least squares method is well described in Schneider's thesis.
  1036.    Briefly, we try to fit the entire curve with one spline.  If that fails,
  1037.    we try reparameterizing, i.e., finding new, and supposedly better,
  1038.    t values.  If that still fails, we subdivide the curve.  */
  1039.  
  1040. static spline_list_type *
  1041. fit_with_least_squares (curve_type curve)
  1042. {
  1043.   real error, best_error;
  1044.   spline_type spline, best_spline;
  1045.   spline_list_type *spline_list;
  1046.   unsigned worst_point;
  1047.   unsigned iteration = 0;
  1048.   real previous_error = FLT_MAX;
  1049.   real improvement = FLT_MAX;
  1050.   
  1051.   LOG ("\nFitting with least squares:\n");
  1052.  
  1053.   /* Phoenix reduces the number of points with a ``linear spline
  1054.      technique''.  But for fitting letterforms, that is
  1055.      inappropriate.  We want all the points we can get.  */
  1056.  
  1057.   /* It makes no difference whether we first set the `t' values or
  1058.      find the tangents.  This order makes the documentation a little
  1059.      more coherent.  */
  1060.  
  1061.   LOG ("Finding tangents:\n");
  1062.   find_tangent (curve, /* to_start */ true,  /* cross_curve */ false);
  1063.   find_tangent (curve, /* to_start */ false, /* cross_curve */ false);
  1064.  
  1065.   set_initial_parameter_values (curve);
  1066.  
  1067.   /* Now we loop, reparameterizing and/or subdividing, until CURVE has
  1068.      been fit.  */
  1069.   while (true)
  1070.     {
  1071.       LOG ("  fitted to spline:\n");
  1072.  
  1073.       spline = fit_one_spline (curve);
  1074.  
  1075.       if (logging)
  1076.         {
  1077.           LOG ("    ");
  1078.           print_spline (log_file, spline);
  1079.         }
  1080.  
  1081.       error = find_error (curve, spline, &worst_point);
  1082.       if (error > previous_error)
  1083.         LOG ("Reparameterization made it worse.\n");
  1084.         /* Just fall through; we will subdivide.  */
  1085.       else
  1086.         {
  1087.           best_error = error;
  1088.           best_spline = spline;
  1089.         }
  1090.  
  1091.       improvement = 1.0 - error / previous_error;
  1092.  
  1093.       /* Don't exit, even if the error is less than `error_threshold',
  1094.          since we might be able to improve the fit with further
  1095.          reparameterization.  If the reparameterization made it worse,
  1096.          we will exit here, since `improvement' will be negative.  */
  1097.       if (improvement < reparameterize_improvement
  1098.           || error > reparameterize_threshold)
  1099.     break;
  1100.  
  1101.       iteration++;
  1102.       LOG3 ("Reparameterization #%u (error was %.3f, a %u%% improvement):\n",
  1103.             iteration, error, ((unsigned) (improvement * 100.0)));
  1104.  
  1105.       /* The reparameterization might fail, if the initial fit was
  1106.          better than `reparameterize_threshold', yet worse than the
  1107.          Newton-Raphson algorithm could handle.  */
  1108.       if (!reparameterize (curve, spline))
  1109.     break;
  1110.  
  1111.       previous_error = error;
  1112.     }
  1113.  
  1114.   /* Go back to the best fit.  */
  1115.   spline = best_spline;
  1116.   error = best_error;
  1117.  
  1118.   if (error < error_threshold)
  1119.     {
  1120.       /* The points were fitted with a (possibly reparameterized)
  1121.          spline.  We end up here whenever a fit is accepted.  We have
  1122.          one more job: see if the ``curve'' that was fit should really
  1123.          be a straight line. */
  1124.       if (spline_linear_enough (&spline, curve))
  1125.         {
  1126.           SPLINE_DEGREE (spline) = LINEAR;
  1127.           LOG ("Changed to line.\n");
  1128.         }
  1129.       spline_list = init_spline_list (spline);
  1130.       LOG1 ("Accepted error of %.3f.\n", error);
  1131.     }
  1132.   else
  1133.     {
  1134.       /* We couldn't fit the curve acceptably, so subdivide.  */
  1135.       unsigned subdivision_index;
  1136.       spline_list_type *left_spline_list;
  1137.       spline_list_type *right_spline_list;
  1138.       curve_type left_curve = new_curve ();
  1139.       curve_type right_curve = new_curve ();
  1140.  
  1141.       /* Keep the linked list of curves intact.  */
  1142.       NEXT_CURVE (right_curve) = NEXT_CURVE (curve);
  1143.       PREVIOUS_CURVE (right_curve) = left_curve;
  1144.       NEXT_CURVE (left_curve) = right_curve;
  1145.       PREVIOUS_CURVE (left_curve) = curve;
  1146.       NEXT_CURVE (curve) = left_curve;
  1147.  
  1148.       REPORT ("s");
  1149.       LOG1 ("\nSubdividing (error %.3f):\n", error);
  1150.       LOG3 ("  Original point: (%.3f,%.3f), #%u.\n",
  1151.             CURVE_POINT (curve, worst_point).x,
  1152.             CURVE_POINT (curve, worst_point).y, worst_point);
  1153.       subdivision_index = find_subdivision (curve, worst_point);
  1154.       LOG3 ("  Final point: (%.3f,%.3f), #%u.\n",
  1155.             CURVE_POINT (curve, subdivision_index).x,
  1156.             CURVE_POINT (curve, subdivision_index).y, subdivision_index);
  1157.       display_subdivision (CURVE_POINT (curve, subdivision_index));
  1158.       
  1159.       /* The last point of the left-hand curve will also be the first
  1160.          point of the right-hand curve.  */
  1161.       CURVE_LENGTH (left_curve) = subdivision_index + 1;
  1162.       CURVE_LENGTH (right_curve) = CURVE_LENGTH (curve) - subdivision_index;
  1163.       left_curve->point_list = curve->point_list;
  1164.       right_curve->point_list = curve->point_list + subdivision_index;
  1165.  
  1166.       /* We want to use the tangents of the curve which we are
  1167.          subdividing for the start tangent for left_curve and the
  1168.          end tangent for right_curve.  */
  1169.       CURVE_START_TANGENT (left_curve) = CURVE_START_TANGENT (curve);
  1170.       CURVE_END_TANGENT (right_curve) = CURVE_END_TANGENT (curve);
  1171.  
  1172.       /* We have to set up the two curves before finding the tangent at
  1173.          the subdivision point.  The tangent at that point must be the
  1174.          same for both curves, or noticeable bumps will occur in the
  1175.          character.  But we want to use information on both sides of the
  1176.          point to compute the tangent, hence cross_curve = true.  */
  1177.       find_tangent (left_curve, /* to_start_point: */ false,
  1178.                     /* cross_curve: */ true);
  1179.       CURVE_START_TANGENT (right_curve) = CURVE_END_TANGENT (left_curve);
  1180.  
  1181.       /* Now that we've set up the curves, we can fit them.  */
  1182.       left_spline_list = fit_curve (left_curve);
  1183.       right_spline_list = fit_curve (right_curve);
  1184.  
  1185.       /* Neither of the subdivided curves could be fit, so fail.  */
  1186.       if (left_spline_list == NULL && right_spline_list == NULL)
  1187.         return NULL;
  1188.  
  1189.       /* Put the two together (or whichever of them exist).  */
  1190.       spline_list = new_spline_list ();
  1191.  
  1192.       if (left_spline_list == NULL)
  1193.         {
  1194.           WARNING ("could not fit left spline list");
  1195.           LOG1 ("Could not fit spline to left curve (%x).\n",
  1196.                 (unsigned) left_curve);
  1197.         }
  1198.       else
  1199.         concat_spline_lists (spline_list, *left_spline_list);
  1200.  
  1201.       if (right_spline_list == NULL)
  1202.         {
  1203.           WARNING ("could not fit right spline list");
  1204.           LOG1 ("Could not fit spline to right curve (%x).\n",
  1205.                 (unsigned) right_curve);
  1206.         }
  1207.       else
  1208.         concat_spline_lists (spline_list, *right_spline_list);
  1209.     }
  1210.  
  1211.   return spline_list;
  1212. }
  1213.  
  1214.  
  1215. /* Our job here is to find alpha1 (and alpha2), where t1_hat (t2_hat) is
  1216.    the tangent to CURVE at the starting (ending) point, such that:
  1217.  
  1218.    control1 = alpha1*t1_hat + starting point
  1219.    control2 = alpha2*t2_hat + ending_point
  1220.  
  1221.    and the resulting spline (starting_point .. control1 and control2 ..
  1222.    ending_point) minimizes the least-square error from CURVE.
  1223.    
  1224.    See pp.57--59 of the Phoenix thesis.
  1225.    
  1226.    The B?(t) here corresponds to B_i^3(U_i) there.
  1227.    The Bernshte\u in polynomials of degree n are defined by
  1228.    B_i^n(t) = { n \choose i } t^i (1-t)^{n-i}, i = 0..n  */
  1229.  
  1230. #define B0(t) CUBE (1 - (t))
  1231. #define B1(t) (3.0 * (t) * SQUARE (1 - (t)))
  1232. #define B2(t) (3.0 * SQUARE (t) * (1 - (t)))
  1233. #define B3(t) CUBE (t)
  1234.  
  1235. #define U(i) CURVE_T (curve, i)
  1236.  
  1237. static spline_type
  1238. fit_one_spline (curve_type curve)
  1239. {
  1240.   /* Since our arrays are zero-based, the `C0' and `C1' here correspond
  1241.      to `C1' and `C2' in the paper.  */
  1242.   real X_C1_det, C0_X_det, C0_C1_det;
  1243.   real alpha1, alpha2;
  1244.   spline_type spline;
  1245.   vector_type start_vector, end_vector;
  1246.   unsigned i;
  1247.   vector_type A[CURVE_LENGTH (curve)][2]; /* A dynamically allocated array.  */
  1248.   vector_type t1_hat = *CURVE_START_TANGENT (curve);
  1249.   vector_type t2_hat = *CURVE_END_TANGENT (curve);
  1250.   real C[2][2] = { { 0.0, 0.0 }, { 0.0, 0.0 } };
  1251.   real X[2] = { 0.0, 0.0 };
  1252.  
  1253.   START_POINT (spline) = CURVE_POINT (curve, 0);
  1254.   END_POINT (spline) = LAST_CURVE_POINT (curve);
  1255.   start_vector = make_vector (START_POINT (spline));
  1256.   end_vector = make_vector (END_POINT (spline));
  1257.  
  1258.   for (i = 0; i < CURVE_LENGTH (curve); i++)
  1259.     {
  1260.       A[i][0] = Vmult_scalar (t1_hat, B1 (U (i)));
  1261.       A[i][1] = Vmult_scalar (t2_hat, B2 (U (i)));
  1262.     }
  1263.  
  1264.   for (i = 0; i < CURVE_LENGTH (curve); i++)
  1265.     {
  1266.       vector_type temp, temp0, temp1, temp2, temp3;
  1267.       vector_type *Ai = A[i];
  1268.  
  1269.       C[0][0] += Vdot (Ai[0], Ai[0]);
  1270.       C[0][1] += Vdot (Ai[0], Ai[1]);
  1271.       /* C[1][0] = C[0][1] (this is assigned outside the loop)  */
  1272.       C[1][1] += Vdot (Ai[1], Ai[1]);
  1273.  
  1274.       /* Now the right-hand side of the equation in the paper.  */
  1275.       temp0 = Vmult_scalar (start_vector, B0 (U (i)));
  1276.       temp1 = Vmult_scalar (start_vector, B1 (U (i)));
  1277.       temp2 = Vmult_scalar (end_vector, B2 (U (i)));
  1278.       temp3 = Vmult_scalar (end_vector, B3 (U (i)));
  1279.  
  1280.       temp = make_vector (Vsubtract_point (CURVE_POINT (curve, i),
  1281.               Vadd (temp0, Vadd (temp1, Vadd (temp2, temp3)))));
  1282.  
  1283.       X[0] += Vdot (temp, Ai[0]);
  1284.       X[1] += Vdot (temp, Ai[1]);
  1285.     }
  1286.  
  1287.   C[1][0] = C[0][1];
  1288.  
  1289.   X_C1_det = X[0] * C[1][1] - X[1] * C[0][1];
  1290.   C0_X_det = C[0][0] * X[1] - C[0][1] * X[0];
  1291.   C0_C1_det = C[0][0] * C[1][1] - C[1][0] * C[0][1];
  1292.   if (C0_C1_det == 0.0)
  1293.     FATAL ("zero determinant of C0*C1");
  1294.  
  1295.   alpha1 = X_C1_det / C0_C1_det;
  1296.   alpha2 = C0_X_det / C0_C1_det;
  1297.  
  1298.   CONTROL1 (spline) = Vadd_point (START_POINT (spline),
  1299.                                   Vmult_scalar (t1_hat, alpha1));
  1300.   CONTROL2 (spline) = Vadd_point (END_POINT (spline),
  1301.                                   Vmult_scalar (t2_hat, alpha2));
  1302.   SPLINE_DEGREE (spline) = CUBIC;
  1303.   
  1304.   return spline;
  1305. }
  1306.  
  1307. /* Find closer-to-optimal t values for the given x,y's and control
  1308.    points, using Newton-Raphson iteration.  A good description of this
  1309.    is in Plass & Stone.  This routine performs one step in the
  1310.    iteration, not the whole thing.  */
  1311.  
  1312. static boolean
  1313. reparameterize (curve_type curve, spline_type S)
  1314. {
  1315.   unsigned p, i;
  1316.   spline_type S1, S2;        /* S' and S''.  */
  1317.  
  1318.   REPORT ("r");
  1319.  
  1320.   /* Find the first and second derivatives of S.  To make
  1321.      `evaluate_spline' work, we fill the beginning points (i.e., the first
  1322.      two for a linear spline and the first three for a quadratic one),
  1323.      even though this is at odds with the rest of the program.  */
  1324.   for (i = 0; i < 3; i++)
  1325.     {
  1326.       S1.v[i].x = 3.0 * (S.v[i + 1].x - S.v[i].x);
  1327.       S1.v[i].y = 3.0 * (S.v[i + 1].y - S.v[i].y);
  1328.     }
  1329.   S1.v[i].x = S1.v[i].y = -1.0;    /* These will never be accessed.  */
  1330.   SPLINE_DEGREE (S1) = QUADRATIC;
  1331.  
  1332.   for (i = 0; i < 2; i++)
  1333.     {
  1334.       S2.v[i].x = 2.0 * (S1.v[i + 1].x - S1.v[i].x);
  1335.       S2.v[i].y = 2.0 * (S1.v[i + 1].y - S1.v[i].y);
  1336.     }
  1337.   S2.v[2].x = S2.v[2].y = S2.v[3].x = S2.v[3].y = -1.0;
  1338.   SPLINE_DEGREE (S2) = LINEAR;
  1339.  
  1340.   for (p = 0; p < CURVE_LENGTH (curve); p++)
  1341.     {
  1342.       real new_distance, old_distance;
  1343.       real_coordinate_type new_point;
  1344.       real_coordinate_type point = CURVE_POINT (curve, p);
  1345.       real t = CURVE_T (curve, p);
  1346.  
  1347.       /* Find the points at this t on S, S', and S''.  */
  1348.       real_coordinate_type S_t = evaluate_spline (S, t);
  1349.       real_coordinate_type S1_t = evaluate_spline (S1, t);
  1350.       real_coordinate_type S2_t = evaluate_spline (S2, t);
  1351.  
  1352.       /* The differences in x and y (Q1(t) on p.62 of Schneider's thesis).  */
  1353.       real_coordinate_type d = { S_t.x - point.x, S_t.y - point.y };
  1354.  
  1355.       /* The step size, f(t)/f'(t).  */
  1356.       real numerator = d.x * S1_t.x + d.y * S1_t.y;
  1357.       real denominator = (SQUARE (S1_t.x) + d.x * S2_t.x
  1358.               + SQUARE (S1_t.y) + d.y * S2_t.y);
  1359.  
  1360.       /* We compute the distances only to be able to check that we
  1361.          really are moving closer.  I don't know how this condition can
  1362.          be reliably checked for in advance, but I know what it means in
  1363.          practice: the original fit was not good enough for the
  1364.          Newton-Raphson iteration to converge.  Therefore, we need to
  1365.          abort the reparameterization, and subdivide.  */
  1366.       old_distance = distance (S_t, point);
  1367.       CURVE_T (curve, p) -= numerator / denominator;
  1368.       new_point = evaluate_spline (S, CURVE_T (curve, p));
  1369.       new_distance = distance (new_point, point);
  1370.  
  1371.       if (new_distance > old_distance)
  1372.     {
  1373.       REPORT ("!");
  1374.       LOG3 ("  Stopped reparameterizing; %.3f > %.3f at point %u.\n",
  1375.         new_distance, old_distance, p);
  1376.       return false;
  1377.     }
  1378.  
  1379.       /* The t value might be negative or > 1, if the choice of control
  1380.          points wasn't so great.  We have no difficulty in evaluating
  1381.          a spline at a t outside the range zero to one, though, so it
  1382.          doesn't matter.  (Although it is a little unconventional.)  */
  1383.     }
  1384.   LOG ("  reparameterized curve:\n   ");
  1385.   log_curve (curve, true);
  1386.  
  1387.   return true;
  1388. }
  1389.  
  1390. /* This routine finds the best place to subdivide the curve CURVE,
  1391.    somewhere near to the point whose index is INITIAL.  Originally,
  1392.    curves were always subdivided at the point of worst error, which is
  1393.    intuitively appealing, but doesn't always give the best results.  For
  1394.    example, at the end of a serif that tapers into the stem, the best
  1395.    subdivision point is at the point where they join, even if the worst
  1396.    point is a little ways into the serif.
  1397.    
  1398.    We return the index of the point at which to subdivide.  */
  1399.          
  1400. static unsigned
  1401. find_subdivision (curve_type curve, unsigned initial)
  1402. {
  1403.   unsigned i, n_done;
  1404.   int best_point = -1;
  1405.   vector_type best = { FLT_MAX, FLT_MAX };
  1406.   unsigned search = subdivide_search * CURVE_LENGTH (curve);
  1407.  
  1408.   LOG1 ("  Number of points to search: %u.\n", search);
  1409.   
  1410.   /* We don't want to find the first (or last) point in the curve.  */
  1411.   for (i = initial, n_done = 0; i > 0 && n_done < search;
  1412.        i = CURVE_PREV (curve, i), n_done++)
  1413.     {
  1414.       if (test_subdivision_point (curve, i, &best))
  1415.         {
  1416.           best_point = i;
  1417.           LOG3 ("    Better point: (%.3f,%.3f), #%u.\n",
  1418.                CURVE_POINT (curve, i).x, CURVE_POINT (curve, i).y, i);
  1419.         }
  1420.     }
  1421.  
  1422.   /* If we found a good one, let's take it.  */
  1423.   if (best_point != -1)
  1424.     return best_point;
  1425.  
  1426.   for (i = CURVE_NEXT (curve, initial), n_done = 0;
  1427.        i < CURVE_LENGTH (curve) - 1 && n_done < search;
  1428.        i = CURVE_NEXT (curve, i), n_done++)
  1429.     {
  1430.       if (test_subdivision_point (curve, i, &best))
  1431.         {
  1432.           best_point = i;
  1433.           LOG3 ("    Better point at (%.3f,%.3f), #%u.\n",
  1434.                CURVE_POINT (curve, i).x, CURVE_POINT (curve, i).y, i);
  1435.         }
  1436.     }
  1437.  
  1438.   /* If we didn't find any better point, return the original.  */
  1439.   return best_point == -1 ? initial : best_point;
  1440. }
  1441.  
  1442.  
  1443. /* Here are some macros that decide whether or not we're at a
  1444.    ``join point'', as described above.  */ 
  1445. #define ONLY_ONE_LESS(v)                        \
  1446.   (((v).dx < subdivide_threshold && (v).dy > subdivide_threshold)    \
  1447.    || ((v).dy < subdivide_threshold && (v).dx > subdivide_threshold))
  1448.  
  1449. #define BOTH_GREATER(v)                            \
  1450.   ((v).dx > subdivide_threshold && (v).dy > subdivide_threshold)
  1451.  
  1452. /* We assume that the vectors V1 and V2 are nonnegative.  */
  1453. #define JOIN(v1, v2)                            \
  1454.     ((ONLY_ONE_LESS (v1) && BOTH_GREATER (v2))                \
  1455.      || (ONLY_ONE_LESS (v2) && BOTH_GREATER (v1)))
  1456.  
  1457. /* If the component D of the vector V is smaller than the best so far,
  1458.    update the best point.  */
  1459. #define UPDATE_BEST(v, d)                        \
  1460.   do                                    \
  1461.     {                                    \
  1462.       if ((v).d < subdivide_threshold && (v).d < best->d)        \
  1463.         best->d = (v).d;                        \
  1464.     }                                    \
  1465.   while (0)
  1466.  
  1467.  
  1468. /* If the point INDEX in the curve CURVE is the best subdivision point
  1469.    we've found so far, update the vector BEST.  */
  1470.  
  1471. static boolean
  1472. test_subdivision_point (curve_type curve, unsigned index, vector_type *best)
  1473. {
  1474.   unsigned count;
  1475.   vector_type in, out;
  1476.   boolean join = false;
  1477.  
  1478.   find_curve_vectors (index, curve, subdivide_surround, &in, &out, &count);
  1479.   
  1480.   /* We don't want to subdivide at points which are very close to the
  1481.      endpoints, so if the vectors aren't computed from as many points as
  1482.      we asked for, don't bother checking this point.  */
  1483.   if (count == subdivide_surround)
  1484.     {
  1485.       in = Vabs (in);
  1486.       out = Vabs (out);
  1487.  
  1488.       join = JOIN (in, out);
  1489.       if (join)
  1490.         {
  1491.           UPDATE_BEST (in, dx);
  1492.           UPDATE_BEST (in, dy);
  1493.           UPDATE_BEST (out, dx);
  1494.           UPDATE_BEST (out, dy);
  1495.         }
  1496.     }
  1497.   
  1498.   return join;
  1499. }
  1500.  
  1501. /* Find reasonable values for t for each point on CURVE.  The method is
  1502.    called chord-length parameterization, which is described in Plass &
  1503.    Stone.  The basic idea is just to use the distance from one point to
  1504.    the next as the t value, normalized to produce values that increase
  1505.    from zero for the first point to one for the last point.  */
  1506.  
  1507. static void
  1508. set_initial_parameter_values (curve_type curve)
  1509. {
  1510.   unsigned p;
  1511.  
  1512.   LOG ("\nAssigning initial t values:\n  ");
  1513.  
  1514.   CURVE_T (curve, 0) = 0.0;
  1515.  
  1516.   for (p = 1; p < CURVE_LENGTH (curve); p++)
  1517.     {
  1518.       real_coordinate_type point = CURVE_POINT (curve, p),
  1519.                            previous_p = CURVE_POINT (curve, p - 1);
  1520.       real d = distance (point, previous_p);
  1521.       CURVE_T (curve, p) = CURVE_T (curve, p - 1) + d;
  1522.     }
  1523.  
  1524.   assert (LAST_CURVE_T (curve) != 0.0);
  1525.  
  1526.   for (p = 1; p < CURVE_LENGTH (curve); p++)
  1527.     CURVE_T (curve, p) = CURVE_T (curve, p) / LAST_CURVE_T (curve);
  1528.  
  1529.   log_entire_curve (curve);
  1530. }
  1531.  
  1532. /* Find an approximation to the tangent to an endpoint of CURVE (to the
  1533.    first point if TO_START_POINT is true, else the last).  If
  1534.    CROSS_CURVE is true, consider points on the adjacent curve to CURVE.
  1535.  
  1536.    It is important to compute an accurate approximation, because the
  1537.    control points that we eventually decide upon to fit the curve will
  1538.    be placed on the half-lines defined by the tangents and
  1539.    endpoints...and we never recompute the tangent after this.  */
  1540.  
  1541. static void
  1542. find_tangent (curve_type curve, boolean to_start_point, boolean cross_curve)
  1543. {
  1544.   vector_type tangent;
  1545.   vector_type **curve_tangent = to_start_point ? &(CURVE_START_TANGENT (curve))
  1546.                                                : &(CURVE_END_TANGENT (curve));
  1547.   unsigned n_points = 0;
  1548.   
  1549.   LOG1 ("  tangent to %s: ", to_start_point ? "start" : "end");
  1550.  
  1551.   if (*curve_tangent == NULL)
  1552.     {
  1553.       *curve_tangent = xmalloc (sizeof (vector_type));
  1554.       tangent = find_half_tangent (curve, to_start_point, &n_points);
  1555.  
  1556.       if (cross_curve)
  1557.         {
  1558.           curve_type adjacent_curve
  1559.             = to_start_point ? PREVIOUS_CURVE (curve) : NEXT_CURVE (curve);
  1560.           vector_type tangent2
  1561.             = find_half_tangent (adjacent_curve, !to_start_point, &n_points);
  1562.           
  1563.           LOG2 ("(adjacent curve half tangent (%.3f,%.3f)) ",
  1564.                 tangent2.dx, tangent2.dy);
  1565.           tangent = Vadd (tangent, tangent2);
  1566.         }
  1567.  
  1568.       assert (n_points > 0);
  1569.       **curve_tangent = Vmult_scalar (tangent, 1.0 / n_points);
  1570.     }
  1571.   else
  1572.     LOG ("(already computed) ");
  1573.  
  1574.   LOG2 ("(%.3f,%.3f).\n", (*curve_tangent)->dx, (*curve_tangent)->dy);
  1575. }
  1576.  
  1577.  
  1578. /* Find the change in y and change in x for `tangent_surround' (a global)
  1579.    points along CURVE.  Increment N_POINTS by the number of points we
  1580.    actually look at.  */
  1581.  
  1582. static vector_type
  1583. find_half_tangent (curve_type c, boolean to_start_point, unsigned *n_points)
  1584. {
  1585.   unsigned p;
  1586.   int factor = to_start_point ? 1 : -1;
  1587.   unsigned tangent_index = to_start_point ? 0 : c->length - 1;
  1588.   real_coordinate_type tangent_point = CURVE_POINT (c, tangent_index);
  1589.   vector_type tangent = { 0.0, 0.0 };
  1590.  
  1591.   for (p = 1; p <= tangent_surround; p++)
  1592.     {
  1593.       int this_index = p * factor + tangent_index;
  1594.       real_coordinate_type this_point;
  1595.  
  1596.       if (this_index < 0 || this_index >= c->length)
  1597.     break;
  1598.  
  1599.       this_point = CURVE_POINT (c, p * factor + tangent_index);
  1600.  
  1601.       /* Perhaps we should weight the tangent from `this_point' by some
  1602.          factor dependent on the distance from the tangent point.  */
  1603.       tangent = Vadd (tangent,
  1604.               Vmult_scalar (Psubtract (this_point, tangent_point),
  1605.                     factor));
  1606.       (*n_points)++;
  1607.     }
  1608.  
  1609.   return tangent;
  1610. }
  1611.  
  1612. /* When this routine is called, we have computed a spline representation
  1613.    for the digitized curve.  The question is, how good is it?  If the
  1614.    fit is very good indeed, we might have an error of zero on each
  1615.    point, and then WORST_POINT becomes irrelevant.  But normally, we
  1616.    return the error at the worst point, and the index of that point in
  1617.    WORST_POINT.  The error computation itself is the Euclidean distance
  1618.    from the original curve CURVE to the fitted spline SPLINE.  */
  1619.  
  1620. static real
  1621. find_error (curve_type curve, spline_type spline, unsigned *worst_point)
  1622. {
  1623.   unsigned this_point;
  1624.   real total_error = 0.0;
  1625.   real worst_error = FLT_MIN;
  1626.   
  1627.   *worst_point = CURVE_LENGTH (curve) + 1;   /* A sentinel value.  */
  1628.   
  1629.   for (this_point = 0; this_point < CURVE_LENGTH (curve); this_point++)
  1630.     {
  1631.       real_coordinate_type curve_point = CURVE_POINT (curve, this_point);
  1632.       real t = CURVE_T (curve, this_point);
  1633.       real_coordinate_type spline_point = evaluate_spline (spline, t);
  1634.       real this_error = distance (curve_point, spline_point);
  1635.  
  1636.       if (this_error > worst_error)
  1637.         {
  1638.           *worst_point = this_point;
  1639.           worst_error = this_error;
  1640.         }
  1641.       total_error += this_error;
  1642.     }
  1643.  
  1644.   if (*worst_point == CURVE_LENGTH (curve) + 1)
  1645.     { /* Didn't have any ``worst point''; the error should be zero.  */
  1646.       if (epsilon_equal (total_error, 0.0))
  1647.     LOG ("  Every point fit perfectly.\n");
  1648.       else
  1649.     WARNING ("No worst point found; something is wrong");
  1650.     }
  1651.   else
  1652.     {
  1653.       LOG4 ("  Worst error (at (%.3f,%.3f), point #%u) was %.3f.\n",
  1654.             CURVE_POINT (curve, *worst_point).x,
  1655.             CURVE_POINT (curve, *worst_point).y, *worst_point, worst_error);
  1656.       LOG1 ("  Total error was %.3f.\n", total_error);
  1657.       LOG2 ("  Average error (over %u points) was %.3f.\n",
  1658.             CURVE_LENGTH (curve), total_error / CURVE_LENGTH (curve));
  1659.     }
  1660.  
  1661.   return worst_error;
  1662. }
  1663.  
  1664. /* Supposing that we have accepted the error, another question arises:
  1665.    would we be better off just using a straight line?  */
  1666.  
  1667. static boolean
  1668. spline_linear_enough (spline_type *spline, curve_type curve)
  1669. {
  1670.   real A, B, C, slope;
  1671.   unsigned this_point;
  1672.   real distance = 0.0;
  1673.  
  1674.   LOG ("Checking linearity:\n");
  1675.   
  1676.   /* For a line described by Ax + By + C = 0, the distance d from a
  1677.      point (x0,y0) to that line is:
  1678.  
  1679.      d = | Ax0 + By0 + C | / sqrt (A^2 + B^2).
  1680.  
  1681.      We can find A, B, and C from the starting and ending points,
  1682.      unless the line defined by those two points is vertical.  */
  1683.      
  1684.   if (epsilon_equal (START_POINT (*spline).x, END_POINT (*spline).x))
  1685.     {
  1686.       A = 1;
  1687.       B = 0;
  1688.       C = -START_POINT (*spline).x;
  1689.     }
  1690.   else
  1691.     {
  1692.       /* Plug the spline's starting and ending points into the two-point
  1693.      equation for a line, that is,
  1694.  
  1695.      (y - y1) = ((y2 - y1)/(x2 - x1)) * (x - x1)
  1696.  
  1697.      to get the values for A, B, and C.  */
  1698.  
  1699.       slope = ((END_POINT (*spline).y - START_POINT (*spline).y)
  1700.            / (END_POINT (*spline).x - START_POINT (*spline).x));
  1701.       A = -slope;
  1702.       B = 1;
  1703.       C = slope * START_POINT (*spline).x - START_POINT (*spline).y;
  1704.     }
  1705.   LOG3 ("  Line is %.3fx + %.3fy + %.3f = 0.\n", A, B, C);
  1706.   
  1707.   for (this_point = 0; this_point < CURVE_LENGTH (curve); this_point++)
  1708.     {
  1709.       real t = CURVE_T (curve, this_point);
  1710.       real_coordinate_type spline_point = evaluate_spline (*spline, t);
  1711.       
  1712.       distance += fabs (A * spline_point.x + B * spline_point.y + C)
  1713.                    / sqrt (A * A + B * B);
  1714.     }
  1715.   LOG1 ("  Total distance is %.3f, ", distance);
  1716.  
  1717.   distance /= CURVE_LENGTH (curve);
  1718.   LOG1 ("which is %.3f normalized.\n", distance);
  1719.   
  1720.   /* We want reversion of short curves to splines to be more likely than
  1721.      reversion of long curves, hence the second division by the curve
  1722.      length, for use in `change_bad_lines'.  */
  1723.   SPLINE_LINEARITY (*spline) = distance / CURVE_LENGTH (curve);
  1724.   LOG1 ("  Final linearity: %.3f.\n", SPLINE_LINEARITY (*spline));
  1725.   
  1726.   return distance < line_threshold;
  1727. }
  1728.  
  1729.  
  1730. /* Unfortunately, we cannot tell in isolation whether a given spline
  1731.    should be changed to a line or not.  That can only be known after the
  1732.    entire curve has been fit to a list of splines.  (The curve is the
  1733.    pixel outline between two corners.)  After subdividing the curve, a
  1734.    line may very well fit a portion of the curve just as well as the
  1735.    spline---but unless a spline is truly close to being a line, it
  1736.    should not be combined with other lines.  */
  1737.  
  1738. static void
  1739. change_bad_lines (spline_list_type *spline_list)
  1740. {
  1741.   unsigned this_spline;
  1742.   boolean found_cubic = false;
  1743.   unsigned length = SPLINE_LIST_LENGTH (*spline_list);
  1744.   
  1745.   LOG1 ("\nChecking for bad lines (length %u):\n", length);
  1746.   
  1747.   /* First see if there are any splines in the fitted shape.  */
  1748.   for (this_spline = 0; this_spline < length; this_spline++)  
  1749.     {
  1750.       if (SPLINE_DEGREE (SPLINE_LIST_ELT (*spline_list, this_spline)) == CUBIC)
  1751.         {
  1752.           found_cubic = true;
  1753.           break;
  1754.         }
  1755.     }
  1756.   
  1757.   /* If so, change lines back to splines (we haven't done anything to
  1758.      their control points, so we only have to change the degree) unless
  1759.      the spline is close enough to being a line.  */
  1760.   if (found_cubic)
  1761.     for (this_spline = 0; this_spline < length; this_spline++)
  1762.       {
  1763.         spline_type s = SPLINE_LIST_ELT (*spline_list, this_spline);
  1764.         
  1765.         if (SPLINE_DEGREE (s) == LINEAR)
  1766.           {
  1767.             LOG1 ("  #%u: ", this_spline);
  1768.             if (SPLINE_LINEARITY (s) > line_reversion_threshold)
  1769.               {
  1770.                 LOG ("reverted, ");
  1771.                 SPLINE_DEGREE (SPLINE_LIST_ELT (*spline_list, this_spline))
  1772.                   = CUBIC;
  1773.               }
  1774.             LOG1 ("linearity %.3f.\n", SPLINE_LINEARITY (s));
  1775.           }
  1776.       }
  1777.     else
  1778.       LOG ("  No lines.\n");
  1779. }
  1780.  
  1781. /* When we have finished fitting an entire pixel outline to a spline
  1782.    list L, we go through L to ensure that any endpoints that are ``close
  1783.    enough'' (i.e., within `align_threshold') to being the same really
  1784.    are the same.  */
  1785.  
  1786. /* This macro adjusts the AXIS axis on the starting and ending points on
  1787.    a particular spline if necessary.  */
  1788. #define TRY_AXIS(axis)                            \
  1789.   do                                    \
  1790.     {                                    \
  1791.       real delta = fabs (end.axis - start.axis);            \
  1792.                                     \
  1793.       if (!epsilon_equal (delta, 0.0) && delta <= align_threshold)    \
  1794.         {                                \
  1795.           spline_type *next = &NEXT_SPLINE_LIST_ELT (*l, this_spline);    \
  1796.           spline_type *prev = &PREV_SPLINE_LIST_ELT (*l, this_spline);    \
  1797.                                     \
  1798.           START_POINT (*s).axis = END_POINT (*s).axis            \
  1799.             = END_POINT (*prev).axis = START_POINT (*next).axis        \
  1800.             = (start.axis + end.axis) / 2;                \
  1801.           spline_change = true;                        \
  1802.         }                                \
  1803.     }                                    \
  1804.   while (0)
  1805.  
  1806. static void
  1807. align (spline_list_type *l)
  1808. {
  1809.   boolean change;
  1810.   unsigned this_spline;
  1811.   unsigned length = SPLINE_LIST_LENGTH (*l);
  1812.   
  1813.   LOG1 ("\nAligning spline list (length %u):\n", length);
  1814.   
  1815.   do
  1816.     {
  1817.       change = false;
  1818.       
  1819.       LOG ("  ");
  1820.       
  1821.       for (this_spline = 0; this_spline < length; this_spline++) 
  1822.         {
  1823.           boolean spline_change = false;
  1824.           spline_type *s = &SPLINE_LIST_ELT (*l, this_spline);
  1825.           real_coordinate_type start = START_POINT (*s);
  1826.           real_coordinate_type end = END_POINT (*s);
  1827.           
  1828.           TRY_AXIS (x);
  1829.           TRY_AXIS (y);
  1830.           if (spline_change)
  1831.             {
  1832.               LOG1 ("%u ", this_spline);
  1833.               change |= spline_change;
  1834.             }
  1835.         }
  1836.       LOG ("\n");
  1837.     }
  1838.   while (change);
  1839. }
  1840.  
  1841. /* Lists of array indices (well, that is what we use it for).  */
  1842.  
  1843. static index_list_type
  1844. new_index_list ()
  1845. {
  1846.   index_list_type index_list;
  1847.  
  1848.   index_list.data = NULL;
  1849.   INDEX_LIST_LENGTH (index_list) = 0;
  1850.  
  1851.   return index_list;
  1852. }
  1853.  
  1854.  
  1855. static void
  1856. free_index_list (index_list_type *index_list)
  1857. {
  1858.   if (INDEX_LIST_LENGTH (*index_list) > 0)
  1859.     {
  1860.       free (index_list->data);
  1861.       index_list->data = NULL;
  1862.       INDEX_LIST_LENGTH (*index_list) = 0;
  1863.     }
  1864. }
  1865.  
  1866.  
  1867. static void
  1868. append_index (index_list_type *list, unsigned new_index)
  1869. {
  1870.   INDEX_LIST_LENGTH (*list)++;
  1871.   XRETALLOC (list->data, INDEX_LIST_LENGTH (*list), unsigned);
  1872.   list->data[INDEX_LIST_LENGTH (*list) - 1] = new_index;
  1873. }
  1874.